package exercise.coroutine.easy.q5;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DbCallbackApi {

    public void query(String sql, Callback<List<String>> callback) {
        // 模拟异步执行
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);

                // 模拟一些查询结果
                if (sql.contains("error")) {
                    // 模拟查询失败
                    throw new RuntimeException("数据库查询错误：无效的SQL");
                }

                // 模拟成功
                List<String> result = new ArrayList<>();
                result.add("记录1" + sql);
                result.add("记录2" + sql);
                callback.onSuccess(result);
            } catch (InterruptedException e) {
                callback.onFailure(new RuntimeException("查询被取消"));
            } catch (Exception e) {
                callback.onFailure(e);
            }
        }).start();
    }
}
